<?php


class Image {
	
	var $id_imagen;
	var $name;
	var $size;
	var $imagetype;
	var $tmp_name;
	var $error;
	var $folder;
	var $_overwrite;
	var $lasterror;
	var $debug;
	var $newname;
	var $userid;
	var $id_producto;
	var $id_academia;
	
	function __construct()
    {
        //parent::__construct();
		$this->name = "";
		$this->size = 0;	
		$this->tmp_name = "";
		$this->error = 0;
		$this->folder = realpath(IMAGE_UPLOAD_DIR).DIRECTORY_SEPARATOR;	
		$this->_overwrite = false;
		$this->id_imagen = 0;
		$this->id_producto = 0;
		$this->debug = false;
		$this->newname ="";
		$this->userid = 0;
		$this->id_academia = 0;
		// campos propios
    }
	
	public function Eliminar($idimagen) {
		$idimagen = intval($idimagen);
		$result = mysql_query("SELECT * FROM imagenes WHERE id_imagen = '$idimagen';");
		if($result && mysql_num_rows($result)>0) {
			$imagen = mysql_fetch_array($result);
			@unlink($imagen['folder'].$imagen['nombre_imagen']);	
			@unlink($imagen['folder']."thumbs/".$imagen['nombre_imagen']);
			mysql_query("DELETE FROM imagenes WHERE id_imagen = '$idimagen';");		
		}
	}
	
	public function setUserId($userid) {
		$this->userid = $userid;	
	}
	
	public function setNewName($nombre) {
		$this->newname = $nombre;	
	}
	
	public function getId() {
		return $this->id_imagen;	
	}
	
	public function getLastError() {
		return $this->lasterror;	
	}
	
	public function isOk() {
		return $this->error==0;
	}
	
	
	public function setFolder($folder) {
		if(substr($folder,strlen($folder)-1,1)!=DIRECTORY_SEPARATOR) {
			$folder.=DIRECTORY_SEPARATOR;	
		}
		$this->folder = realpath($folder).DIRECTORY_SEPARATOR;
		
	}
	
	
	public function Overwrite($switch) {
		// true or false
		$this->__overwrite = $switch;	
	}
	
	function resize($width = 0, $height = 0, $thumb = false) {
		if($this->error!=0) return false;
		$proportional = true;
		$file = $this->folder.$this->name;
		$outputfile = $file;
		$delete_original = true;
		if($thumb==true) {
			if(!is_dir($this->folder."thumbs")) mkdir($this->folder."thumbs");
			$outputfile = $this->folder."thumbs/".$this->name;	
			$delete_original = false;
		}
		$output = "file";
		$use_linux_commands = false;
      	if ( $height <= 0 && $width <= 0 ) {
      		$width = 110;
			$height = 118;
		}

		$info = getimagesize($file);
		$image = '';
		$final_width = 0;
		$final_height = 0;
		list($width_old, $height_old) = $info;
		if(empty($width_old) ||empty($height_old)) {
			$this->lasterror = "La imagen no puede ser procesada";
			$this->error = 1;
			return false;	
		}

		if ($proportional) {
		  if ($width == 0) $factor = $height/$height_old;
		  elseif ($height == 0) $factor = $width/$width_old;
		  else $factor = min ( $width / $width_old, $height / $height_old);  
		  $final_width = round ($width_old * $factor);
		  $final_height = round ($height_old * $factor);
		}
		else {
		  $final_width = ( $width <= 0 ) ? $width_old : $width;
		  $final_height = ( $height <= 0 ) ? $height_old : $height;
		}

		switch ( $info[2] ) {
		  case IMAGETYPE_GIF:
			$image = imagecreatefromgif($file);
		  break;
		  case IMAGETYPE_JPEG:
			$image = imagecreatefromjpeg($file);
		  break;
		  case IMAGETYPE_PNG:
			$image = imagecreatefrompng($file);
		  break;
		  default:
			return false;
		}   
    	$image_resized = imagecreatetruecolor( $final_width, $final_height );
       
		if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
		  $trnprt_indx = imagecolortransparent($image);
	   
		  // If we have a specific transparent color
		  if ($trnprt_indx >= 0) {
			// Get the original image's transparent color's RGB values
			$trnprt_color    = imagecolorsforindex($image, $trnprt_indx);
			// Allocate the same color in the new image resource
			$trnprt_indx    = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
			// Completely fill the background of the new image with allocated color.
			imagefill($image_resized, 0, 0, $trnprt_indx);
			// Set the background color for new image to transparent
			imagecolortransparent($image_resized, $trnprt_indx);
		  }
		  // Always make a transparent background color for PNGs that don't have one allocated already
		  elseif ($info[2] == IMAGETYPE_PNG) {
			// Turn off transparency blending (temporarily)
			imagealphablending($image_resized, false);
			// Create a new transparent color for image
			$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
			// Completely fill the background of the new image with allocated color.
			imagefill($image_resized, 0, 0, $color);
			// Restore transparency blending
			imagesavealpha($image_resized, true);
		  }
		}
		imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);
		if ( $delete_original ) {
			@unlink($file);
		}
		switch ( strtolower($output) ) {
		  case 'browser':
			$mime = image_type_to_mime_type($info[2]);
			header("Content-type: $mime");
			$output = NULL;
		  break;
		  case 'file':
			$output = $outputfile;
		  break;
		  case 'return':
			return $image_resized;
		  break;
		  default:
		  break;
		}
		switch ( $info[2] ) {
		  case IMAGETYPE_GIF:
			imagegif($image_resized, $output);
		  break;
		  case IMAGETYPE_JPEG:
			imagejpeg($image_resized, $output);
		  break;
		  case IMAGETYPE_PNG:
			imagepng($image_resized, $output);
		  break;
		  default:
			return false;
		}
		$size = filesize($output);
		//$idimagen = $this->id;
		if($thumb==false) $this->size = $size;
		return true;
	}
	
	private function msg($variable,$titulo = "") {
		echo("<pre>");
		if($titulo!="") echo($titulo.": \n");
		print_r($variable);
		echo("</pre><br>");	
	}
	
	private function separar($nombreimagen) {
		$partes = explode(".",$nombreimagen);
		if(count($partes)==1) {
			return array($nombreimagen,"gif");	
		}
		$ext = end($partes);
		$ret = "";
		foreach($partes as $k) {
			$k= str_replace(" ","_",$k);
			if($k!=$ext) $ret.=$k;
		}
		if(strlen($ret)>30) $ret = substr($ret,0,30);
		return array($ret,$ext);
	}
	
	private function getImage() {
		if(!is_array($_FILES)) return false;
		$file = $_FILES['archivo'];
		$this->name = str_replace(" ","_",$file['name']);
		if(empty($this->name)) {
			$this->lasterror = "Debe especificar un archivo";	
			$this->error=1;
			return false;			
		}
		$this->imagetype = $file['type'];
		$this->tmp_name = $file['tmp_name'];
		$this->error = intval($file['error']);
		$this->size = $file['size'];
		//tratamiento del nombre	
		if($this->debug){
			 $this->msg($file,"subiendo ".$this->name." para ".$this->folder);
			 $this->msg($this->error,"error");
		}		
		$imageninfo = getimagesize($this->tmp_name);
		if(!$imageninfo) {
			$this->error=1;
			$this->lasterror = "La imagen tiene un formato desconocido";
			return false;	
		}
		if($this->error==0) {	
			list($nombre,$ext) = $this->separar($this->name);
			$i=0;
			if($this->newname!="") $this->name = $nombre.".".$ext; 
			$oldname = $this->name;
			if(!$this->_overwrite) {
				while(file_exists($this->folder.$oldname)) {						
					$nombre = substr($this->name,0,strlen($this->name)-strlen($ext)-1).$i;
					if($this->debug) {
						$this->msg($nombre,"nombre");
						$this->msg($ext,"extension");
					}
					$i++;
					$oldname = $nombre.".".$ext;
				}
				$this->name=$oldname;
			} else {
				if(file_exists($this->folder.$this->name)) {
					@unlink($this->folder.$this->name);	
				}
			}
			if(file_exists($this->tmp_name)) {
				@copy($this->tmp_name,$this->folder.$this->name);
				@unlink($this->tmp_name);					
			}
			list($width, $height, $type, $attr) = getimagesize($this->folder.$this->name);
			$mime = strtolower(image_type_to_mime_type($type));
			if(		strpos($mime,"jpeg")!==false  &&
					strpos($mime,"png")!==false &&
					strpos($mime,"gif")!==false &&

					strpos($mime,"jpg")!==false)  {						
					$this->error = 1;
					$this->lasterror = "Solo se pueden subir archivos de imagenes";
					@unlink($this->folder.$this->name);
					return false;
			}						
		
			// cambiar el tamano y crear el thumbnail
			if($width>200) $this->resize(200,0);// cambia el tamano a 200px		
			$this->resize(100,100,true); // crea un thumb de 100px
			return true;
		}		
		return false;
	}
	
	
	public function getUpload() {
		if(!$_POST['verif']) exit();
		$id_persona = $_POST['id_persona']?intval($_POST['id_persona']):0;
		$id_academia = $_POST['id_academia']?intval($_POST['id_academia']):0;
		if($id_persona==0 && $id_academia==0)  {
			$this->lasterror = "Debe especificar la entidad";
			$this->error = 0;
			return false;
		}		
		$this->id_persona = $id_persona;	
		$this->id_academia = $id_academia;
		$hayimagen = $this->getImage();
		$campos = array(
			"nombre_imagen" => $this->name,
			"size" => $this->size,
			"imagetype" => $this->imagetype,
			"folder" => $this->folder,
			"id_persona" => $this->id_persona,	
			"id_academia" => $this->id_academia,	
			"ip_address" => $_SERVER['REMOTE_ADDR'],
			"stamp" => time()
		);
		if(!$hayimagen) {
			$this->lasterror = "Debe especificar una imagen";
			$this->error=1;	
			return false;
		}		
		// borrar imagen anterior
		if($id_persona>0) $img = db::getArray("SELECT id_imagen FROM imagenes WHERE id_persona = '$id_persona'");
		if($id_academia>0) $img = db::getArray("SELECT id_imagen FROM imagenes WHERE id_academia = '$id_academia'");
		foreach($img as $id) $this->Eliminar($id);
		$nombres = array();
		$valores = array();
		foreach($campos as $k => $v) {
			 $nombres[]=$k;
			 $valores[]="'".$v."'";
		}		
		$query = "INSERT INTO imagenes (__NOMBRES__) VALUES (__VALORES__)";	
		$query = str_replace("__NOMBRES__",implode(", ",$nombres),$query);
		$query = str_replace("__VALORES__",implode(", ",$valores),$query);			
		$result = mysql_query($query);	
		if($result) { 
			$this->id_imagen = mysql_insert_id(); 		
		} else {
			$this->lasterror = "No se pudo ejecutar consulta";
			return false;	
		}
		return true;
	}	
	
}
?>